
package net.biaji.android.alephclient;

import net.biaji.alephclient.LibAgent;
import net.biaji.android.alephclient.account.Authenticator;
import net.biaji.android.alephclient.account.LoginActivity;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.Menu;
import android.widget.SearchView;

public class MainActivity extends FragmentActivity implements BookDetailShower,
        SearchView.OnQueryTextListener {

    private String username = "", password = "";
    
    private SearchView bookSearcher;

    private MainInfoFragment infoF;

    private final int ACTION_LOGIN = 1;

    private LibAgent agent;

    private final static String FRAGMENT_TAG_MAININFO = "MAININFO";

    private final static String FRAGMENT_TAG_SEARCHRESULT = "SEARCHRESULT";

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (infoF != null)
                infoF.load();
        }

    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AccountManager am = AccountManager.get(this);
        Account[] accounts = am.getAccountsByType(Authenticator.ACCOUNT_TYPE);
        if (accounts.length == 0) {
            Intent intent = new Intent(this, LoginActivity.class);
            startActivityForResult(intent, ACTION_LOGIN);
        } else {
            username = accounts[0].name;
            password = am.getPassword(accounts[0]);
            agent = AgentSingleton.getInstance(username, password, handler);

        }

        setContentView(R.layout.activity_main);

    }

    @Override
    protected void onStart() {
        super.onStart();
        infoF = new MainInfoFragment();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.main_frag_container, infoF, FRAGMENT_TAG_MAININFO);
        transaction.commit();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);

        bookSearcher = (SearchView) menu.findItem(R.id.menu_search_widget).getActionView();
        if (bookSearcher != null) {
            bookSearcher.setOnQueryTextListener(this);
        }

        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case ACTION_LOGIN:

                break;

            default:
                break;
        }
    }

    private void searchBook(String query) {
        SearchResultFragment searchFrag = (SearchResultFragment) getSupportFragmentManager()
                .findFragmentByTag(FRAGMENT_TAG_SEARCHRESULT);
        if (searchFrag == null) {
            searchFrag = new SearchResultFragment();
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.main_frag_container, searchFrag, FRAGMENT_TAG_SEARCHRESULT);
            transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            transaction.addToBackStack(null);
            transaction.commit();
        }
        searchFrag.search(query);
    }

    public void onBookSelected(String docNumber) {

        if (docNumber == null)
            return;

        BookDetailFragment detailFrag = new BookDetailFragment();
        Bundle args = new Bundle();
        args.putString(BookDetailFragment.KEY_DOC_NUMBER, docNumber);
        detailFrag.setArguments(args);

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.main_frag_container, detailFrag);
        transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        transaction.addToBackStack(null);
        transaction.commit();

    }

    @Override
    public boolean onQueryTextChange(String newText) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        if(query == null || query.length()==0)
            return true;
        searchBook(query);
        
        bookSearcher.clearFocus();

        
        return true;
    }
}
